package cn.sunxyz.common;

import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Supplier;

/**
 * Created by yangrd on 2017/3/24.
 */
public class Pipeline<T> {

    private T t;

    private Pipeline<T> pipeline;

    Pipeline(T t) {
        this.t = t;
        this.pipeline = this;
    }

    public static <T> Pipeline<T> of(T t) {
        return new Pipeline<T>(t);
    }

    public static <T> Pipeline<T> of(Supplier<T> supplier) {
        return of(supplier.get());
    }

    public Pipeline<T> setter(Consumer<T> action) {
        action.accept(t);
        return pipeline;
    }

    public static <T> Pipeline<T> setter(Supplier<T> supplier, Consumer<T> action) {
        T t = supplier.get();
        action.accept(t);
        return of(t);
    }

    public static <T> T buildObj(Supplier<T> supplier, Consumer<T> action) {
        return setter(supplier, action).get();
    }

    public T get() {
        return t;
    }

    public Optional<T> getOption() {
        return Optional.of(t);
    }

    static class Stu {
        String name, sex;
        Integer age;

        @Override
        public String toString() {
            return "Stu{" +
                    "name='" + name + '\'' +
                    ", sex='" + sex + '\'' +
                    ", age=" + age +
                    '}';
        }
    }

    public static void main(String[] args) {
        Stu stu = Pipeline.of(Stu::new)
                .setter(s -> {
                    s.name = "456";
                    s.sex = "man";
                    s.age = 6;
                }).get();
        Stu stu1 = Pipeline
                .setter(Stu::new, s -> {
                    s.name = "456";
                    s.sex = "man";
                    s.age = 6;
                }).get();
        Stu stu2 = Pipeline
                .buildObj(Stu::new, s -> {
                    s.name = "456";
                    s.sex = "man";
                    s.age = 6;
                });
        Stu stu3 = Optional.of(new Stu())
                .map(s -> {
                    s.name = "456";
                    s.sex = "man";
                    s.age = 6;
                    return s;
                }).get();
        System.out.printf("stu: %s ,stu1: %s", stu, stu1);
    }
}
